﻿namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Web;
    using System.Web.Routing;

    public class GuidConstraint : IRouteConstraint
    {
        private readonly bool optional;

        public GuidConstraint() : this(false)
        {
        }

        public GuidConstraint(bool optional)
        {
            this.optional = optional;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            var value = values[parameterName];

            if (value == null)
            {
                return optional;
            }

            var matched = false;
            Guid guid;

            if (Guid.TryParse(value.ToString(), out guid) && (guid != Guid.Empty))
            {
                matched = true;
            }

            return matched;
        }
    }
}